<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/8/31
 * Time: 15:44
 */

namespace app\index\server;


use app\index\model\User as UserModel;
use app\lib\exception\DatabaseException;
use think\Exception;

class UserServer extends BaseServer
{
    public function getList($params = [])
    {
        // 参数的准备
        $prep_params = $this->prep_param($params);
        try {
            // 总条数
            $count = UserModel::count();
            $banner_list = UserModel::with(['agent', 'gAgent', 'pAgent'])
                ->order($prep_params['sort'], $prep_params['order'])
                ->limit($prep_params['offset'], $prep_params['limit'])
                ->select();
        } catch (Exception $e) {
            throw new DatabaseException([
                'msg' => $e->getMessage()
            ]);
        }
        return bootstrap_table_return($count, $banner_list);
    }

    public function detail($id)
    {
        try {
          $info = UserModel::where('id', $id)
              ->find();
          if(!$info) {
              return setMsg(0, '未找到此信息');
          }
        }catch (Exception $e) {
            throw new DatabaseException([
                'msg' => $e->getMessage()
            ]);
        }
        return setMsg(1, 'OK', $info);
    }

    public function changeStatus($id)
    {
        try{
            $info = UserModel::where('id', $id)->find();
            $info->status = abs( ($info->status) - 1 );
            $result = $info->save();
            if(!$result){
                return setMsg(0, '修改用户状态失败');
            }
        }catch(Exception $e){
            throw new DatabaseException([
                'msg' => $e->getMessage()
            ]);
        }
        return setMsg(1, '修改用户状态成功');
    }

    public function update($params = [])
    {
        $prep_data = [
            'qq' => $params['qq'],
            'email' => $params['email'],
            'mobile' => $params['mobile'],
            'status' => $params['status']
        ];
        try {
            $result = UserModel::where('id', $params['primary_key'])
                ->update($prep_data);
            if(!$result) return setMsg(1, '修改用户信息失败');
        } catch (Exception $e) {
            throw new DatabaseException([
                'msg' => $e->getMessage()
            ]);
        }
        return setMsg(1, '修改用户信息成功');
    }
}